package talkbot;

import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.xmpp.*;
import java.util.logging.Logger;

@SuppressWarnings("serial")
public class DudeTalkServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(DudeTalkServlet.class.getName());

	private static final XMPPService xmpp = XMPPServiceFactory.getXMPPService();

	/**
	 * Main function which will receive requests
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)	throws IOException {

		Message message = xmpp.parseMessage(req);
		JID fromJid = message.getFromJid();
		
		String body = message.getBody();
		String response = "DUDE!!";
		String sEmail = fromJid.getId().split("/")[0];
		
		// we log input data
		log.info(sEmail + " told me '" + body + "'");
		
		if (!this.sendInstantMessage(fromJid, response)) {
			log.info("Message could not be sent");
		}

	}
	
	/**
	 * Sends a given instant message to specified user 
	 * @param toJid
	 * @param body
	 * @return
	 */
	public boolean sendInstantMessage(JID toJid, String body) {

		Message msg = new MessageBuilder()
		.withRecipientJids(toJid)
		.withBody(body)
		.build();

		boolean messageSent = false;

		if (xmpp.getPresence(toJid).isAvailable()) {
			SendResponse status = xmpp.sendMessage(msg);
			messageSent = (status.getStatusMap().get(toJid) == SendResponse.Status.SUCCESS);
		}

		return messageSent;

	}

}